import React, { useRef, useState, useEffect } from 'react'
import { Modal, Form, Input, DatePicker, Select, InputNumber, Upload, Button, message, Space } from 'antd'
import { awaitWrap, getUploadPropsFn, strToNum } from '@js/tool'
import { UploadOutlined } from '@ant-design/icons'
import style from './Modal.module.less'
import { submitFiles } from '@js/request'
import { addRequest, updateRequest } from './ajax'
import moment from 'moment'
const { Item } = Form
const { Option } = Select
const { TextArea } = Input

async function submitHandle (d, status, refreshFn) {
  const id = d.id
  if (!validateData(d)) {
    return false
  }
  const hide = message.loading('提交中')
  formatData(d)
  const file = d.file ? d.file instanceof Array ? d.file : d.file.fileList : []
  let fileid = ''
  if (file.length) {
    try {
      fileid = await submitFiles(file)
    } catch (e) {
      return message.warning('上传图片失败')
    }
  } else {
    hide()
    return message.warning('封面不能为空')
  }
  delete d.file
  d.thumbnailid = fileid
  if (typeof id === 'string') {
    updateHandle(id, d, () => { refreshFn(); hide() })
  } else {
    d.status = status
    addHandle(d, () => { refreshFn(); hide() })
  }
}

function validateData (data) {
  if (data.begin_datetime > data.end_datetime) {
    message.warning('开始时间不能晚于结束时间')
    return false
  }
  return true
}

function formatData (data) {
  data.begin_datetime = Math.floor(moment(`${data.begin_datetime.format('YYYY-MM-DD HH:mm')}:00`).valueOf() / 1000)
  data.end_datetime = Math.floor(moment(`${data.end_datetime.format('YYYY-MM-DD HH:mm')}:59`).valueOf() / 1000)
  data.registration_deadline = Math.floor(data.registration_deadline.valueOf() / 1000)
}

async function addHandle (d, refresh) {
  const [e] = await awaitWrap(addRequest(d))
  if (e === null) {
    message.success('新增成功')
    refresh()
  } else {
    message.error(e.message)
  }
}

async function updateHandle (id, d, refresh) {
  const [e] = await awaitWrap(updateRequest(id, d))
  if (e === null) {
    message.success('编辑成功')
    refresh()
  } else {
    message.error(e.message)
  }
}

function Main ({ data, visible, hide, refreshFn }) {
  const formRef = useRef(null)
  const [fileList, setFileList] = useState([])
  const [status, setStatus] = useState('草稿')
  const [startable, setStartable] = useState(false)
  useEffect(() => {
    if (visible) {
      setStartable(data === null || data.status === '草稿')
      if (formRef.current !== null && data) {
        const d = { ...data }
        d.file = d.thumbnail_file || []
        d.begin_datetime = strToNum(d.begin_datetime)
        d.end_datetime = strToNum(d.end_datetime)
        d.registration_deadline = strToNum(d.registration_deadline)
        d.begin_datetime = d.begin_datetime > 0 ? moment(d.begin_datetime * 1000) : undefined
        d.end_datetime = d.end_datetime > 0 ? moment(d.end_datetime * 1000) : undefined
        d.registration_deadline = d.registration_deadline > 0 ? moment(d.registration_deadline * 1000) : undefined
        formRef.current.setFieldsValue(d)
        d.file.forEach(li => { li.name = li.original_filename })
        setFileList(d.file)
      }
    } else if (!visible && formRef.current !== null) {
      formRef.current.resetFields()
      setFileList([])
    }
  }, [data, visible])
  return (
    <Modal
      title={data !== null ? '编辑直播' : '新增直播'} width={600} open={visible} onCancel={hide} footer={(
        <Space>
          <Button onClick={hide}>取消</Button>
          <Button type='primary' ghost onClick={() => { setStatus(data === null ? '草稿' : data.status); formRef.current.submit() }}>保存</Button>
          {startable && <Button type='primary' onClick={() => { setStatus('报名'); formRef.current.submit() }}>开启报名</Button>}
        </Space>
      )}
    >
      <Form ref={formRef} labelCol={{ flex: '108px' }} onFinish={d => submitHandle(d, status, () => { hide(); refreshFn() })}>
        <Item name='id' noStyle><span /></Item>
        <Item label='会议名称' name='title' rules={[{ required: true, message: '标题不能为空' }]}>
          <Input placeholder='请输入' />
        </Item>
        <Item label='会议开始时间' name='begin_datetime' rules={[{ required: true, message: '会议开始时间不能为空' }]}>
          <DatePicker className={style.full} format='YYYY-MM-DD HH:mm' showTime />
        </Item>
        <Item label='会议结束时间' name='end_datetime' rules={[{ required: true, message: '会议结束时间不能为空' }]}>
          <DatePicker className={style.full} format='YYYY-MM-DD HH:mm' showTime />
        </Item>
        <Item label='报名截止日期' name='registration_deadline' rules={[{ required: true, message: '报名截止日期不能为空' }]}>
          <DatePicker className={style.full} format='YYYY-MM-DD HH:mm' showTime />
        </Item>
        <Item label='会议类型' name='isonline' rules={[{ required: true, message: '会议类型不能空' }]}>
          <Select placeholder='请选择'>
            <Option value={1}>线上直播</Option>
            <Option value={0}>线下开会</Option>
          </Select>
        </Item>
        <Item label='会议简介' name='content' rules={[{ required: true, message: '会议简介不能为空' }]}>
          <TextArea rows={3} placeholder='请输入' />
        </Item>
        <Item label='参会人数' name='participant_no' rules={[{ required: true, message: '参会人数不能为空' }]}>
          <InputNumber placeholder='请输入' className={style.full} min={0} max={2000} />
        </Item>
        <Item label='会议地址' name='address'>
          <Input placeholder='请输入' />
        </Item>
        <Item label='开放范围' name='open_range' rules={[{ required: true, message: '开放范围不能为空' }]}>
          <Select placeholder='请选择'>
            <Option value='公开'>公开</Option>
            <Option value='非公开'>非公开</Option>
          </Select>
        </Item>
        <Item name='file' label='上传封面' rules={[{ required: true, message: '封面不能为空' }]}>
          <Upload {...getUploadPropsFn.call(this, formRef, '.jpg,.jpeg,.png', fileList, setFileList)}>
            <Button disabled={fileList.length > 0}>
              <UploadOutlined /> 上传文件
            </Button>
            <span className={style['upload-placeholder']}>图像大小：355px * 248px，支持扩展名：.png .jpg</span>
          </Upload>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
